import axios, { AxiosResponse, AxiosError } from 'axios';
import { message } from 'antd';

const instance = axios.create({
  baseURL: process.env.REACT_APP_API_URL || '',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    if (data.code === 200) {
      return data.data;
    }
    throw new Error(data.message || '请求失败');
  },
  (error: AxiosError) => {
    const response = error.response?.data as any;
    const errorMessage = response?.message || error.message || '请求失败';
    message.error(errorMessage);
    return Promise.reject(new Error(errorMessage));
  }
);

export const request = {
  get: <T>(url: string, params?: any) => 
    instance.get<any, T>(url, { params }),

  post: <T>(url: string, data?: any) => 
    instance.post<any, T>(url, data),

  put: <T>(url: string, data?: any) => 
    instance.put<any, T>(url, data),

  delete: <T>(url: string) => 
    instance.delete<any, T>(url),
}; 